package br.slic.services;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import br.slic.eao.GenericEAO;
import br.slic.entidade.EntidadePersistente;
import br.slic.exception.EAOException;
import br.slic.exception.ServiceException;
import br.slic.services.interfaces.GenericServiceLocal;
import br.slic.util.DadosUtil;

@Stateless
public class GenericService implements GenericServiceLocal {

	@PersistenceContext(unitName=GenericEAO.UNIT_NAME)
	private EntityManager em;	
	
	@SuppressWarnings("rawtypes")
	@Override
	public <T> void remover(List<T> objetos, Class clazz) throws ServiceException {
		try {
			GenericEAO<T> eao = new GenericEAO<T>(clazz, em);
			for(T obj : objetos) {
				eao.remove(obj);				
			}
		} catch (EAOException e) {
			throw new ServiceException(e.getMessage());
		}		
	}	

	@SuppressWarnings("rawtypes")
	@Override
	public <T> void persistir(T objeto, Class clazz) throws ServiceException {
		try {
			GenericEAO<T> eao = new GenericEAO<T>(clazz, em);
			eao.persist(objeto);
		} catch (EAOException e) {
			throw new ServiceException(e.getMessage());
		}				
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public <T extends EntidadePersistente> void salvar(T objeto, Class clazz) throws ServiceException {
		if (DadosUtil.isEmpty(objeto.getId())) {
			persistir(objeto, clazz);			
		} else {
			atualizar(objeto, clazz);
		}
	}	
	
	@SuppressWarnings("rawtypes")
	@Override
	public <T> void atualizar(T objeto, Class clazz) throws ServiceException {
		try {
			GenericEAO<T> eao = new GenericEAO<T>(clazz, em);
			eao.saveOrUpdate(objeto);
		} catch (EAOException e) {
			throw new ServiceException(e.getMessage());
		}				
	}
	

	@SuppressWarnings("rawtypes")
	@Override
	public <T> T obterEntidade(Long id, Class clazz) throws ServiceException {
		try {
			GenericEAO<T> eao = new GenericEAO<T>(clazz, em);
			T objeto = eao.selectById(id);
			return objeto;
		} catch (EAOException e) {
			throw new ServiceException(e.getMessage());
		}
	}

	@SuppressWarnings("rawtypes")
	@Override
	public <T> List<T> obterEntidades(Class clazz) throws ServiceException {
		try {
			GenericEAO<T> eao = new GenericEAO<T>(clazz, em);
			List<T> objetos = eao.getAll();
			return objetos;
		} catch (EAOException e) {
			throw new ServiceException(e.getMessage());
		}
	}

	@SuppressWarnings("rawtypes")
	@Override
	public <T> List<T> obterListaLazy(Object objeto, Class clazz, String relacionamento) throws ServiceException {
		try {
			GenericEAO<T> eao = new GenericEAO<T>(clazz, em);
			List<T> objetos = eao.loadLazyRelationship(objeto, relacionamento);
			return objetos;
		} catch (EAOException e) {
			throw new ServiceException(e.getMessage());
		}
	}	
	
}
